package com.xiaomaoguai.jdk.thread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Description :
 * @FileName: CountDownLatchDemo.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年6月25日 下午5:21:54
 * @Version:V1.00
 */
public class CountDownLatchDemo {

	public class Worker implements Runnable {

		private CountDownLatch latch;
		private String name;

		public Worker(String name, CountDownLatch latch) {
			this.name = name;
			this.latch = latch;
		}

		@Override
		public void run() {
			doWork();
			try {
				TimeUnit.SECONDS.sleep(new Random().nextInt(5));
				// 完成任务，使count减1
				latch.countDown();
				
				System.out.println("当前线程名称:" + Thread.currentThread().getName() + "  , ID : " + Thread.currentThread().getId());
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(name + ": 我的工作完成了");
		}

		public void doWork() {
			System.out.println(name + "：正在工作");
		}

	}

	public class Boss implements Runnable {

		private CountDownLatch latch;

		Boss(CountDownLatch latch) {
			this.latch = latch;
		}

		@Override
		public void run() {
			try {
				// 一直阻塞，直到Worker完成工作
				latch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Boss检查工作");
		}

	}

	public void test() {
		CountDownLatch latch = new CountDownLatch(3);
		ExecutorService executor = Executors.newFixedThreadPool(4);

		Worker worker1 = new Worker("张三", latch);
		Worker worker2 = new Worker("李斯", latch);
		Worker worker3 = new Worker("王五", latch);
		Boss boss = new Boss(latch);
		executor.execute(worker1);
		executor.execute(worker2);
		executor.execute(worker3);
		executor.execute(boss);
		executor.shutdown();
	}

	public static void main(String[] args) {
		new CountDownLatchDemo().test();
	}

}
